<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template #title>
            <div style="font-size: 15px;font-weight: 400;color: #333;"><span>条件查询</span></div>
        </template>
        <template #icon="{ isActive }">
          <div class="icon-ele">{{ isActive ? '展开' : '折叠' }}</div>
        </template>
        <div class="top-main">
          <el-row>
            <el-col :span="22">
              <el-form :model="searchForm" :inline="true"  label-width="100px">
                <el-form-item label="箱号">
                  <MultipleBoxNumbersDialog v-model="searchForm.containerNo" clearable/>
                </el-form-item>
                <el-form-item label="业务编号">
                  <el-input v-model="searchForm.businessNo" clearable  placeholder="输入业务编号"/>
                </el-form-item>
                <el-form-item label="箱型">
                  <el-select v-model="searchForm.boxType" style="width:100%" placeholder="选择箱型" clearable>
                    <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="箱况">
                  <el-select v-model="searchForm.boxCondition" style="width:100%" placeholder="选择箱况" clearable>
                    <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="提箱日期">
                  <el-date-picker v-model="searchForm.inDate" type="daterange" clearable range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"/>
                </el-form-item>
                <el-form-item label="还箱日期">
                  <el-date-picker v-model="searchForm.outDate" type="daterange" clearable range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"/>
                </el-form-item>
                <el-form-item label="箱东公司">
                  <el-input v-model="searchForm.companyName" clearable placeholder="输入集装箱公司名字"/>
                </el-form-item>
                <el-form-item  label="用箱天数">
                  <el-input v-model="searchForm.beginUseDay" placeholder="结果>=所输入的天数" oninput="value=value.replace(/[^\d]/g,''); if(value<=0) value='';" clearable/>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="2">
              <el-row justify="center">
                <el-col :span="24" class="text-center"><el-button @click="handleReSet" :icon="Refresh">重置</el-button></el-col>
                <el-col :span="24" class="text-center marginTop17"><el-button @click="getTableData" :icon="Search" type="primary">查询</el-button></el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-collapse-item>
    </el-collapse>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange"></cz-tages>
    <span style="margin-top: 5px;float: right;">
      <el-dropdown placement="top" :hide-on-click="false" class="floatLeft" style="margin-right: 12px;">
        <el-button :icon="Grid" type="primary" size="small">自定义显示列</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <div class="mt-2" style="min-width: 600px;">
                <el-checkbox-group v-model="showTableItem" @change="handleGroupChange" :min="5" class="checkbox-grid">
                  <el-row style="width: 100%;">
                      <el-col :span="4" v-for="(item,index) in table.header"  :key="index">
                        <el-checkbox  :label="item.title" :value="item.key" size="small" />
                      </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有数据" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="selectAll" plain class="floatLeft">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="floatLeft">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" class="floatLeft" @click="toExportMyRentBox" plain>导出</el-button>
      <el-button type="primary" size="small" class="floatLeft" @click="batchApply" plain>还箱申请</el-button>
    </span>
    <Table ref="tableRef" v-bind="table" style="width: 100%;" :allId="allId" :isAllCheck="isAllCheck"
           @pageChange="onTablePageChange" @showInfo="showInfo"
           @updateSelectAll="updateSelectAll" @handleBuyBox="handleBuyBox"
           :disableHeaderCheckbox="disableHeaderCheckbox"  @hxView="hxView" @hxApply="hxApply" @sortChange="sortChange">
    </Table>
    <!--dialog -->
    <!-- info -->
    <el-dialog v-model="param.dialogInfoVisible" style="width: 800px;">
      <span class="_before">租箱详情</span>
      <el-row class="marginTop20">
        <el-col :span="8">箱号：{{ param.boxInfo.containerNo || '--' }}</el-col><el-col :span="8">箱型：{{ filters.boxType[param.boxInfo.boxType] || '--' }}</el-col><el-col :span="8">箱况：{{ filters.boxCondition[param.boxInfo.boxCondition] || '--' }}</el-col>
        <el-col :span="8" class="marginTop10">总重:{{ param.boxInfo.boxType <= 10 ? '30480/32500' : '30480' }}</el-col><el-col :span="8" class="marginTop10">提箱日期：{{ formatDate(param.boxInfo.packingDate, 2) || '--' }}</el-col><el-col :span="8" class="marginTop10">还箱日期：{{ formatDate(param.boxInfo.returnDate, 2) || '--' }}</el-col>
        <el-col :span="8" class="marginTop10">箱使期：{{  param.boxInfo.boxUsagePeriod || 0 }} 天</el-col><el-col :span="8" class="marginTop10">已用天数：{{ param.boxInfo.useDays || 0 }} 天</el-col><el-col :span="8" class="marginTop10">超期天数：{{ param.boxInfo.outDays - param.boxInfo.boxUsagePeriod || 0 }} 天</el-col>
        <el-col :span="8" class="marginTop10">状态：{{ filters.status[param.boxInfo.status] || '--' }} </el-col><el-col :span="8" class="marginTop10">实时位置：{{ param.boxInfo.location }} </el-col>
        <el-col :span="8" class="marginTop10 text-ellipsis">
          <el-tooltip effect="dark" :content="param.boxInfo.companyName" placement="top">
            <span>集装箱公司：{{ param.boxInfo.companyName }}</span>
          </el-tooltip>
        </el-col>
        <el-col :span="8" class="marginTop10">城市：{{ param.boxInfo.returnCityName || '--'  }}</el-col><el-col :span="8" class="marginTop10">国家：{{ param.boxInfo.returnCountryName || '--' }}</el-col>
      </el-row>
    </el-dialog>

    <!-- 还箱 -->
    <el-drawer v-model="hxApplyDialog" :with-header="false" size="40%">
        <span class="_before">还箱申请</span>
        <el-row class="marginTop20">
            <el-col :span="24">类型：
                <el-radio-group v-model="returnBoxTypeValue" v-if="showType =='apply' || showType == 'batch'">
                    <el-radio :value="10">箱属</el-radio>
                    <el-radio :value="15">还箱令</el-radio>
                    <!-- <el-radio :value="5">还箱单</el-radio> -->
                </el-radio-group>
                <span v-else-if="showType =='view'">{{{5:'还箱单',10:'箱属',15:'还箱令',null:'无数据'}[txjlInfo.returnBoxType]}}</span>
            </el-col>
        </el-row>
        <div v-if="showType =='batch'">
            箱号：
            <template v-for="(item,index) in txjlSelectionInfo" :key="index">
                {{item.containerNo}} <template v-if="index < (txjlSelectionInfo.length -1)">、</template>
            </template>
        </div>
        <el-row v-else class="marginTop20">
            <el-col :span="8">箱号：{{txjlInfo.containerNo}}</el-col>
            <el-col :span="16" class="text-ellipsis">还箱地：
                <template v-if="txjlInfo.returnCity">
                    <el-tooltip effect="dark" :content="splitSrray(txjlInfo.returnCity)" placement="top">{{splitSrray(txjlInfo.returnCity)}}</el-tooltip>
                </template>
                <template v-else>--</template>
            </el-col>
        </el-row>
        <template v-if="showType =='apply'">
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 10">
                <el-col :span="3">提箱照片：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef5" :limit="10" :urlList="JSON.parse(txjlInfo.detailFileList || '[]')" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" align="center" v-if="returnBoxTypeValue == 15">
                <el-col :span="5" class="_asterisk">预计还箱日期：</el-col>
                <el-col :span="10"><el-date-picker v-model="planReturnDate" type="date" :disabled-date="disabledDate" placeholder="还箱日期" style="width: 100%;"/></el-col>
            </el-row>
            <el-row class="marginTop20 _asterisk" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">到站运单：</el-col>
                <el-col :span="24" class="marginTop5" v-if="showType =='apply'">
                    <ImgUpload ref="packingRef6" :limit="10" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :fileSize="5" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
                <el-col :span="24" class="marginTop5" v-else-if="showType =='view'">
                <ImgUpload ref="packingRef6" :urlList="JSON.parse(txjlInfo.arrivalWaybill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">转关单：</el-col>
                <el-col :span="24" class="marginTop5" v-if="showType =='apply'">
                    <ImgUpload ref="packingRef7" :limit="10" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :fileSize="5" :drag="true" :showNumber="6"></ImgUpload>
                </el-col>
                <el-col :span="24" class="marginTop5" v-else-if="showType =='view'">
                <ImgUpload ref="packingRef7" :urlList="JSON.parse(txjlInfo.turnCustomBill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
        </template>
        <template v-else-if="showType =='view'">
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 10">
                <el-col :span="3">提箱照片：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef5" :urlList="JSON.parse(txjlInfo.detailFileList || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" align="center" v-if="returnBoxTypeValue == 15">
                <el-col :span="5" class="_asterisk">预计还箱日期：</el-col>
                <el-col :span="10">{{formatDate(txjlInfo.planReturnDate,2)}}</el-col>
            </el-row>
            <el-row class="marginTop20 _asterisk" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">到站运单：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef6" :urlList="JSON.parse(txjlInfo.arrivalWaybill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
            <el-row class="marginTop20" v-if="returnBoxTypeValue == 15">
                <el-col :span="3">转关单：</el-col>
                <el-col :span="24" class="marginTop5">
                    <ImgUpload ref="packingRef7" :urlList="JSON.parse(txjlInfo.turnCustomBill || '[]')" :hideUpload="true" :displayType="0" :fileSize="5" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
                </el-col>
            </el-row>
        </template>

        <el-row class="marginTop50" v-if="showType == 'apply' || showType == 'batch'">
            <el-col :span="23" class="text-right">
                <el-button type="primary" @click="submitApplication">确认</el-button>
            </el-col>
        </el-row>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {formatDate} from '@/utils'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { buyBox, exportMyRentBox, getMyRentBoxInfo, getMyRentBoxTable, getMyRentBoxTable as getTable, statusCount ,batchReturnApply} from '@/api/boxRent/mine'
import {onMounted, reactive, ref, nextTick} from 'vue';
import {Finished, Refresh, Search, Upload,Grid} from '@element-plus/icons-vue'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import {formatContainerNo} from '@/utils/mlpBox'
import {downloadFile} from '@/utils/download'
import {ElMessage, ElMessageBox} from 'element-plus'
import ImgUpload from '@/components/upload/uploadFiles-Images'
import { returnApply } from '@/api/orderManage/packingDetail'
import { useRouter, useRoute} from 'vue-router';
const activeNames = ref(['0'])
const showTableItem = ref<string[]>([])
  const route = useRoute();
const handleGroupChange = () => {
  sessionStorage.setItem(String(route.name), JSON.stringify(showTableItem.value));
  table.header.forEach(item => {
    item.isCheck = showTableItem.value.includes(item.key)
  })
}
const param = reactive({
  value1: [],
  boxInfo: {code: '123456789', type: "40HQ", info: "无"},
  dialogTableVisible: false,
  dialogInfoVisible: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  companyName: null,
  options: [{
    value: 'Option1',
    label: '40HQ',
  },
    {
      value: 'Option2',
      label: '40GP',
    }],

  statusOptions: [
    {value: null, label: '全部',},
    {value: '5', label: '已提',},
    {value: '10', label: '未还',},
    {value: '15', label: '还箱中',},
    {value: '20', label: '已还',},
    {value: '25', label: '已买',},
  ],
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    {value: '5', label: '40HQ',},
    {value: '10', label: '40GP',},
    {value: '15', label: '20HQ',},
    {value: '20', label: '20GP',},
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    {value: '15', label: '适货',},
    {value: '10', label: '次新',},
    {value: '5', label: '全新',},
    // { value: '20', label: '混提(次新或者适货)', },
  ],
  inDate: [],
  outDate: [],
  status:''

});

const filters = ref({
  status: {5: '已提', 10: '未还', 15: '还箱中', 20: '已还', 25: '已买'}, //我的租箱状态：5-已提  10-未还  15-还箱中  20-已还 25-已买
  boxType: {5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP'},
  boxCondition: {5: '全新', 10: '次新', 15: '适货', 20: '混提'},
  containerClassify: {5: '租箱', 10: '回调', 15: '外调'} //5-租箱 10-回调 15-外调
})

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'containerNo',key2: 'oidContainerNo',colWidth: '130',title: '箱号',type: '<a>',command: 'showInfo',isCheck: true},
    { key: 'businessNo', colWidth: '130', title: '业务编号', type: 'text', isCheck: true},
    { key: 'boxType',colWidth: '70',title: '箱型',type: 'filter',filter: {5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP'},isCheck: true},
    { key: 'boxCondition',colWidth: '60',title: '箱况',type: 'filter',filter: {5: '全新', 10: '次新', 15: '适货'},isCheck: true},
    { key: 'location', colWidth: '120', title: '实时位置', type: 'text', isCheck: true},
    { key: 'packingDate', colWidth: '120', title: '提箱日期', type: 'date', sortable:'custom', isCheck: true},
    { key: 'boxUsagePeriod', colWidth: '70', title: '箱使期', type: 'text', isCheck: true},
    { key: 'useDays', colWidth: '120', title: '已用天数', type: 'text',sortable:'custom', isCheck: true},
    { key: 'returnDate', colWidth: '120', title: '还箱日期', type: 'date', sortable:'custom', isCheck: true},
    { key: 'overdueDays', colWidth: '120', title: '超期天数', sortable:'custom', type: 'filter1', 
      cFilter: (row: any) => {
        if (row.overdueDays < 0) {
          return '#F56C6C'
        }
      }, isCheck: true
    },
    {
      key: 'status', colWidth: '80', title: '状态', type: 'filter',
      filter: filters.value.status, // 5-已提  10-未还  15-还箱中  20-已还 25-已买
      cFilter: {5: '#22A86D', 10: '#2158F3', 15: '#909399', 20: '#909399', 25: '#22A86D'}, isCheck: true
    },
    { key:'carryCityName', colWidth: '90', title: '提箱城市', type: 'text', isCheck: true },
    { key:'returnCity', colWidth: '150', title: '还箱城市', type: 'moreCity', isCheck: true },
    // {
    //   key: 'payStatus', colWidth: '100', title: '支付状态', type: 'filter',
    //   filter: { 5: '未付', 10: '支付中', 15: '已付' }, // 5-未付 10-支付中 15-已付
    //   isCheck: true
    // },
    {key: 'companyName', colWidth: '300', title: '集装箱公司', type: 'text', isCheck: true},
    {
      key: 'operate',
      colWidth: '100',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          icon: 'Message',
          command: 'handleBuyBox',
          content: '购买',
          isShow: (row: { status: string; }) => {
            return row.status == '25';
          },
        },
        {
          command: 'hxApply',
          name: '还箱申请',     
          isShow: (row: any) => {
             return row.status < 12;   //5-已提 10-未还 12-已申请  15-还箱中  20-已还 25-已买
          },
        },
        {
          command: 'hxView',
          name: '查看申请',
          isShow: (row: any) => { 
             return row.status  >= 12 //5-已提 10-未还 12-已申请  15-还箱中  20-已还 25-已买
          },
        }
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

// 获取列表数据
const searchForm = reactive({
  containerNo: '',
  boxType: '',
  boxCondition: '',
  companyName: '',
  status: '',
  inDate: [],
  outDate: [],
  pageNum: 1,
  pageSize: 10,
  businessNo:'',
  beginUseDay:''
})

const sortBeans = ref([])
function getTableData() {
  const {container, containerList} = formatContainerNo(searchForm.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    boxType: searchForm.boxType,
    boxCondition: searchForm.boxCondition,
    companyName: searchForm.companyName?.trim(),
    pageNum: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    businessNo:searchForm.businessNo,
    beginUseDay:searchForm.beginUseDay,
    sortBeans:sortBeans.value,
    status: param.status,
  };
  if (searchForm.status) {
    data.statusList = [searchForm.status - 0]
  }
  if (searchForm.inDate && searchForm.inDate.length > 1) {
    data.beginPackingDate = searchForm.inDate[0]
    data.endPackingDate = searchForm.inDate[1]
  }
  if (searchForm.outDate && searchForm.outDate.length > 1) {
    data.beginReturnDate = searchForm.outDate[0]
    data.endReturnDate = searchForm.outDate[1]
  }
  getStatusCount(data)
  getMyRentBoxTable(data).then(res => {
    table.data = res.data.list;
    table.config.total = res.data.total;
  });
}
// 5-已提  10-未还  15-还箱中  20-已还 25-已买
const typeList = ref([
    { id: 0, name: '全部',num:0 },
    { id: 5, name: '已提',num:0 },
    { id: 10, name: '未还',num:0 },
    { id: 15, name: '还箱中',num:0 },
    { id: 20, name: '已还',num:0 },
    { id: 25, name: '已买',num:0 },
])
// 还箱单状态: 5-已发放 10-已下载 15-还箱中 20-已完成 25-已过期
// 查询各还箱状态的数量
const getStatusCount = async(data:any) => { 
  await statusCount(data).then((res: any) => {
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //已发放
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10){ //已下载
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //还箱中
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //已完成
              item.num += item1.totalQty
          }else if(item.id == 25 && item1.status == 25){ //已完成
              item.num += item1.totalQty
          }
        })
      })
    }
  })
}

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}
//重置
function handleReSet() {
  searchForm.containerNo = null
  searchForm.boxType = null
  searchForm.boxCondition = null
  searchForm.status = null
  searchForm.companyName = null
  searchForm.inDate = []
  searchForm.outDate = []
  searchForm.businessNo = null
  getTableData()
}

//详情
const showInfo = (row: any) => {
  getMyRentBoxInfo(row.id).then(res => {
    param.boxInfo = res.data
  })
  param.dialogInfoVisible = true;
};

//buy
const handleBuyBox = (row: any) => {
  buyBox(row.id)
};

//分页
function onTablePageChange(page: any) {
  searchForm.pageNum = page.pageNum;
  searchForm.pageSize = page.pageSize;
  console.log(param)
  getTableData();
};


//
onMounted(() => {
  getTableData();
  const showTableItemStr = sessionStorage.getItem(String(route.name))
  if(sessionStorage.getItem(String(route.name))?.length && showTableItemStr){
    showTableItem.value =  JSON.parse(showTableItemStr)
  }else{
    table.header.forEach(item=>{
      showTableItem.value.push(item.key)
    })
  }
  handleGroupChange()
})


const tableRef = ref()
const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const selectAll = async () => {
  checkAll.value = []
  let data = {
    pageNum: 1,
    pageSize: 10000,
  }
  await getTable(data).then(res => {
    if (res.code == "00000" && res.data.list && res.data.total) {
      isSelectAll.value = false
      disableHeaderCheckbox.value = true
      res.data.list.forEach(item => {
        checkAll.value.push(item)
      })
      isAllCheck.value = true
      allId.value = checkAll.value
      tableRef.value.checkAll()
    } else {
      ElMessage.error("全选失败，请刷新页面，或者手动选择")
    }
  })
}
const deselectAll = () => {
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
}


// 订单列表导出
const toExportMyRentBox = () => {
  let checkAllItem = []
  if (isSelectAll.value) {
    checkAllItem = tableRef.value.multipleSelection
  } else {
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的出口集装箱！')
  ElMessageBox.confirm('确认要导出选中的出口集装箱', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportMyRentBox(ids).then((res: any) => {
      downloadFile(res, '出口集装箱信息')
    }).catch((error:any) => {
      ElMessage.error(error)
    })
  }).catch(() => {
  });
}



const hxApplyDialog = ref(false)
const txjlInfo = ref({})
const returnBoxTypeValue = ref(10)
const planReturnDate = ref(new Date())
const showType = ref('apply')
const packingRef5 = ref()
const packingRef6 = ref()
const packingRef7 = ref()
// 查看还箱申请
const hxView = (row:any) => {
  showType.value = 'view'
  nextTick(() => {
        packingRef5.value?.clearFiles()
        packingRef6.value?.clearFiles()
        packingRef7.value?.clearFiles()

        txjlInfo.value = row  
        returnBoxTypeValue.value = txjlInfo.value.returnBoxType || 10
        hxApplyDialog.value = true
    })

}
// 还箱申请
const hxApply = (row:any) => {
    showType.value = 'apply'
    returnBoxTypeValue.value = 10
    planReturnDate.value = new Date()
    nextTick(() => {
        packingRef5.value?.clearFiles()
        packingRef6.value?.clearFiles()
        packingRef7.value?.clearFiles()

        txjlInfo.value = row  
        returnBoxTypeValue.value = txjlInfo.value.returnBoxType || 10
        hxApplyDialog.value = true
    })
}

//批量还箱申请
const txjlSelectionInfo = ref([])
const batchApply = () => { 
  showType.value = 'batch'
  returnBoxTypeValue.value = 10
  let checkAllItem = []
  if (isSelectAll.value) {
    checkAllItem = tableRef.value.multipleSelection
  } else {
    checkAllItem = allId.value
  }
  // const ids = checkAllItem.map((item: any) => item.id)
  txjlSelectionInfo.value = checkAllItem
  if(txjlSelectionInfo.value.length < 1) return ElMessage.warning('请选择需要申请还箱的集装箱')
  nextTick(() => {
      packingRef5.value?.clearFiles()
      packingRef6.value?.clearFiles()
      packingRef7.value?.clearFiles()
      hxApplyDialog.value = true
  })
}

const submitApplication = async() => {
  if(showType.value == 'batch'){
        let txRecordarr = []
        txjlSelectionInfo.value.forEach(item => {
            let record = {id:item.id, returnBoxType: returnBoxTypeValue.value}
            txRecordarr.push(record)
        });
        await batchReturnApply(txRecordarr).then(res => {
            if(res.code == "00000"){
              getTableData()
              hxApplyDialog.value = false
              ElMessage.success("还箱申请发送成功")
            }else{
                ElMessage.warning(res.msg)
            }
        })
    }else{
        let data = {
            returnBoxType: returnBoxTypeValue.value,
        }
        if(returnBoxTypeValue.value == 10){ //箱属
            data.detailFileList = JSON.stringify(packingRef5.value.fileList)
        }else if(returnBoxTypeValue.value == 15){ //还箱令
            data.planReturnDate = planReturnDate.value.toISOString(),
            data.arrivalWaybill = JSON.stringify(packingRef6.value.fileList)
            data.turnCustomBill = JSON.stringify(packingRef7.value.fileList)
        }
        await returnApply(txjlInfo.value.id,data).then(res => {
            if(res.code == "00000"){
                getTableData()
                hxApplyDialog.value = false
                ElMessage.success("还箱申请发送成功")
            }else{
                ElMessage.warning(res.msg)
            }
        })
    }
}
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

// 表格数据排序
const sortChange = (row:any) =>{ 
  sortBeans.value.length = 0
  sortBeans.value.push(row)
  getTableData()
}

// / 多个城市拼接
const splitSrray = (row:any) => {
  let newRow = []
  try{
    newRow = JSON.parse(row)
  }catch(e){
    newRow = []
  }
  let newRowStr = ''
  const newRowLength = newRow.length
  newRow.forEach((item,index) => { 
    if(index < newRowLength - 1){
      newRowStr += item.returnCityName + "、"
    }else{
      newRowStr += item.returnCityName
    } 
  })
  return newRowStr || '--'
}
</script>

<style scoped lang="scss">
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
// 为折叠面板图标添加样式
:deep(.el-collapse-item__header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-ele {
  flex-shrink: 0;
  padding-right: 15px;
}
</style>
